// pages/estate/list/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
formatTime = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    customIndexList: [1, 2, 3, 4, 5, 6, 8, 9, 10],
    scrollTop: 0,
    estates:[],
    estate_names:[],
    keyword:'',
    is_change:0,
    is_band:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.is_change){
      this.data.is_change = parseInt(options.is_change);
    }
    if(options.is_band){
      this.data.is_band = parseInt(options.is_band);
    }
    this.onHttpInit()
  },

  onSearch(val){
    console.log('onSearch',val)
    this.data.keyword = val.detail;
    this.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/estate/listByCharacters', {
      keyword: that.data.keyword,
      is_band: that.data.is_band,
    }, function (res) {
      console.log("账号绑定 数据", res)
      if(res.data.code == 0){
        that.setData({
          estates : res.data.data.estates,
        })
      }
      that.setData({
        netWork: true,
      })
    }, function () {
        that.setData({ netWork: false, hasData: false })
    })
  },
  chooseEstate(e){
    var estateId = e.currentTarget.dataset.estateid;
    var estateName = e.currentTarget.dataset.estatename;    
    // wx.navigateTo({
    //   url: 'url',
    // })
    if(this.data.is_change == 1){
      console.log('estateId', estateId)
      console.log('estateName', estateName)
      this.onHttpUpdateEstate(estateId, estateName);
    }else{      
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2]; //上一个页面
      prevPage.setData({
        estate_id: estateId,
        estate_name: estateName,
        action:'change_estate'
      })
      console.log('pages prevPage 2 ',prevPage)
      wx.navigateBack({ delta: -1 });
    }
  },
  
  onHttpUpdateEstate(estate_id,estate_name){
    var that = this;
    fetchApi.httpPost('/user/updateEstateId', { 
      estate_id: estate_id, 
    }, function (res) {
        if(res.data.code == 0){
          Toast.success(res.data.msg);

          let telphone = res.data.data.estate_telphone;

          app.setStorageSync("estate_id", estate_id);
          app.setStorageSync("estate_name", estate_name);
          app.setStorageSync("estate_telphone", telphone);
          
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.setData({
            estate_id: estate_id,
            estate_name: estate_name,
            action:'change_estate'
          })
          console.log('pages prevPage 2 ',prevPage)
          wx.navigateBack({ delta: -1 });

        }else{
          Toast.fail(res.data.msg)
        }
    });
  },

})